import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo02_DateSoure {
    public static void main(String[] args) {
        //定义Mysql数据源对象
        MysqlDataSource mysqlDataSource=new MysqlDataSource();
        //设置数据库连接
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/java113?characterEncoding=utf8" +
        "&allowPublicKeyRetrieval=true&useSSL=false");
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("123456");
        //定义JDBC数据源对象
        DataSource dataSource=mysqlDataSource;
        //定义连接对象
        Connection connection=null;
        //定义处理SQL执行对象
        PreparedStatement preparedStatement=null;//可解决sql注入问题
        //定义结果集对象
        ResultSet resultSet=null;
        try {
            //1.通过数据源获得数据库连接
            connection=dataSource.getConnection();
            //2.获取处理SQL执行对象
            String sql="select student_id,sn,name from student where name = ?";
            preparedStatement=connection.prepareStatement(sql);
            //接受用户输入
            System.out.println("请输入学生姓名：");
            Scanner scanner=new Scanner(System.in);
            //接收用户输入
            String name=scanner.nextLine();
            //3.用真实值替换占位符
            preparedStatement.setString(1,name);
            //4.执行SQL，获取结果
            resultSet= preparedStatement.executeQuery();
            //5.遍历结果集
            while (resultSet.next()){
                long stuId = resultSet.getLong(1);
                String stuSn = resultSet.getString(2);
                String stuName = resultSet.getString(3);
                System.out.println(MessageFormat.format("学生编号={0},学生学号={1},学生姓名={2}",stuId,stuSn,stuName));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //依次释放资源，关闭链接
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(preparedStatement!=null){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
